package com.kunsan.compose.compoents.login

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.kunsan.compose.R
import com.kunsan.compose.ui.theme.Color3D3D3D
import com.kunsan.compose.ui.theme.LineColor
import com.kunsan.compose.ui.theme.MyApplicationTheme
import com.kunsan.compose.ui.theme.primaryColor
import com.kunsan.compose.ui.theme.Color666666


@Composable
fun LoginScreen(navigateToHome: () -> Unit = {}, viewModel: LoginViewModel = viewModel()) {


    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 37.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Spacer(modifier = Modifier.height(100.dp))

        Image(
            painter = painterResource(id = R.drawable.icon_login_app_logo),
            contentDescription = "Account Icon"
        )

        Spacer(modifier = Modifier.height(42.dp))

        PhoneSmsCodeLogin()

        Spacer(modifier = Modifier.height(36.dp))

        PrivacyAndAgreement()

        Spacer(modifier = Modifier.height(8.dp))

        FilledTonalButton(
            onClick = {
                navigateToHome.invoke()
            },
            shape = RoundedCornerShape(6.dp),
            colors = ButtonDefaults.buttonColors(containerColor = primaryColor),
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("登录", modifier = Modifier.padding(vertical = 6.dp), fontSize = 14.sp)
        }
    }
    BackHandler {
    }
}

@Composable
private fun PhoneSmsCodeLogin() {

    var phoneNum by remember { mutableStateOf("") }
    var phoneSmsCode by remember { mutableStateOf("") }
    var hasFocus by remember { mutableStateOf(false) }

    val maxPhoneLength = 11
    val maxSmsCodeLength = 6

    Column(horizontalAlignment = Alignment.CenterHorizontally) {

        Row(verticalAlignment = Alignment.CenterVertically) {
            Image(
                painter = painterResource(id = R.drawable.icon_login_phone_num),
                contentDescription = "Account Icon",
                modifier = Modifier.padding(end = 8.dp) // 图标和文本框之间的间距
            )

            BasicTextField(
                value = phoneNum,
                modifier = Modifier
                    .height(44.dp)
                    .onFocusChanged { hasFocus = it.isFocused },
                textStyle = TextStyle(
                    fontSize = 14.sp,
                    color = Color666666
                ),
                onValueChange = {
                    if (it.length <= maxPhoneLength) phoneNum = it.trim()
                },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone),
                decorationBox = { innerTextField ->
                    Row(
                        Modifier.border(1.dp, LineColor, RoundedCornerShape(6.dp))
                    ) {
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .height(44.dp)
                                .padding(horizontal = 19.dp),
                            contentAlignment = Alignment.CenterStart
                        ) {
                            if (phoneNum.isEmpty()) {
                                Text(
                                    text = "请输入手机号",
                                    modifier = Modifier.align(Alignment.CenterStart),
                                    color = Color666666,
                                    fontSize = 14.sp
                                )
                            }
                            innerTextField()

                            if (hasFocus && phoneNum.isNotEmpty()) {
                                Image(imageVector = Icons.Filled.Clear,
                                    contentDescription = "",
                                    modifier = Modifier
                                        .align(Alignment.CenterEnd)
                                        .clickable {
                                            phoneNum = ""
                                        })
                            }
                        }

                    }
                }
            )
        }


        Spacer(modifier = Modifier.height(19.dp))


        Row(verticalAlignment = Alignment.CenterVertically) {
            Image(
                painter = painterResource(id = R.drawable.icon_login_sms_code),
                contentDescription = "Account Icon",
                modifier = Modifier.padding(end = 8.dp) // 图标和文本框之间的间距
            )
            BasicTextField(
                value = phoneSmsCode,
                modifier = Modifier
                    .height(44.dp),
                textStyle = TextStyle(
                    fontSize = 14.sp,
                    color = Color666666
                ),
                onValueChange = {
                    if (it.length <= maxSmsCodeLength) phoneSmsCode = it.trim()
                },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
                decorationBox = { innerTextField ->
                    Row(
                        Modifier.border(1.dp, LineColor, RoundedCornerShape(6.dp))
                    ) {
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .height(44.dp)
                                .padding(start = 19.dp, end = 5.dp),
                            contentAlignment = Alignment.CenterStart
                        ) {
                            if (phoneSmsCode.isEmpty()) {
                                Text(
                                    text = "请输入验证码",
                                    modifier = Modifier.align(Alignment.CenterStart),
                                    color = Color666666,
                                    fontSize = 14.sp
                                )
                            }
                            innerTextField()
                            Button(
                                onClick = {}, shape = RoundedCornerShape(6.dp),  // 设置圆角
                                colors = ButtonDefaults.buttonColors(containerColor = primaryColor),
                                modifier = Modifier
                                    .padding(vertical = 6.dp)
                                    .align(Alignment.CenterEnd),
                                contentPadding = PaddingValues(
                                    start = 0.dp, end = 0.dp, top = 0.dp, bottom = 0.dp
                                )
                            ) {
                                Text(
                                    "发送验证码",
                                    modifier = Modifier.padding(horizontal = 12.dp),
                                    fontSize = 12.sp
                                )
                            }
                        }

                    }
                }
            )
        }
    }
}

@Composable
fun PrivacyAndAgreement() {
    val checkedState = remember { mutableStateOf(false) }
    Row(
        modifier = Modifier
            .fillMaxWidth(),
        verticalAlignment = Alignment.Top, // 设置元素顶部对齐
        horizontalArrangement = Arrangement.spacedBy(2.dp)
    ) {
        CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides Dp.Unspecified) {
            Checkbox(
                modifier = Modifier.scale(0.8f),
                checked = checkedState.value, onCheckedChange = { checkedState.value = it },
                colors = CheckboxDefaults.colors(
                    checkedColor = primaryColor,  // 选中时的颜色
                    uncheckedColor = LineColor,  // 未选中时的颜色
                )
            )
        }

        val text = buildAnnotatedString {
            append("已阅读并同意")
            append(" 以及")
            withStyle(style = SpanStyle(color = primaryColor)) {
                append("用户协议")
            }
            append(" 和")
            withStyle(style = SpanStyle(color = primaryColor)) {
                append("隐私政策")
            }
        }
        Text(
            text = text, modifier = Modifier.align(Alignment.Top), fontSize = 12.sp
        )
    }
}


@Composable
fun OnClickLogin(routePhoneCodeLogin: () -> Unit) {

    val localPhoneNum by remember { mutableStateOf("1445") }
    val serviceProvider by remember { mutableStateOf("XXXX") }

    Column(
        modifier = Modifier
            .fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(fontSize = 24.sp, text = localPhoneNum)

        Spacer(modifier = Modifier.height(10.dp))
        Text(fontSize = 14.sp, color = Color666666, text = "认证服务由$serviceProvider 提供")

        Spacer(modifier = Modifier.height(23.dp))

        FilledTonalButton(
            onClick = {
            },
            colors = ButtonDefaults.buttonColors(containerColor = primaryColor),
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(6.dp)
        ) {
            Text("本机号码一键登录", modifier = Modifier.padding(vertical = 6.dp), fontSize = 14.sp)
        }
        Spacer(modifier = Modifier.height(24.dp))

        OutlinedButton(
            onClick = {
                routePhoneCodeLogin.invoke()
            },
            modifier = Modifier
                .fillMaxWidth(),
            border = BorderStroke(1.dp, LineColor),
            shape = RoundedCornerShape(6.dp),

            ) {
            Text(
                "其他手机号码登录",
                modifier = Modifier.padding(vertical = 6.dp),
                color = Color3D3D3D,
                fontSize = 14.sp
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    MyApplicationTheme {
        LoginScreen()
    }
}